/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package alloytoy;

import java.io.*;
import java.util.*;
import java.util.logging.*;

/**
 * Methods that read tex files with alloy models. The models are within check_marks and
 * these functions extract the models from tex files.
 * @author Daniel
 */
class TexParser{
    String fileName;
    ArrayList<String> names;
    ArrayList<String> dirNames;
    int count;
    public TexParser(String file){
        fileName = file;
        names = new ArrayList<String>();
        dirNames = new ArrayList<String>();
        count=0;
    }

    public ArrayList<String> getNames(){
        return names;
    }

    public ArrayList<String> getDirNames(){
        return dirNames;
    }

    //New Section in Tex File.
    //If section has alloycode, a new dir is built with name: Checknumber
    private void NewSection(int number, BufferedReader bout, String dir) throws IOException{
        String line="";        
        while((line = bout.readLine())!=null){
            if(line.indexOf("\\begin{moduleutil}")==0){
                if(!(new File(dir+"/Check"+number)).exists()){
                    boolean nice = (new File(dir+"/Check"+number)).mkdir();
                    if(!nice){
                        System.out.println("CANNOT CREATE DIR: Check"+number+".");
                        System.out.println("PLEASE CHECK YOUR PERMISSIONS.");
                        System.exit(0);
                    }
                    dirNames.add(dir+"/Check"+number);
                }
                else{
                    dirNames.add(dir+"/Check"+number);

                 }
                BufferedWriter bwrite = new BufferedWriter(new FileWriter(dir+"/Check"+number+"/Dif"+number,true));
                //System.out.println(name);
                names.add("Dif"+number);
                line = bout.readLine();
                //System.out.println(line.indexOf("\\end{lstlisting}"));
                while(line!=null && line.indexOf("\\end{moduleutil}")==-1){
                    //System.out.println(line);
                    bwrite.write(line);
                    bwrite.newLine();
                    line = bout.readLine();
                }
                bwrite.newLine();
                bwrite.flush();
                bwrite.close();
            }
            
            if(line.indexOf("\\begin{lstlisting}")==0){
                if(!(new File(dir+"/Check"+number)).exists()){
                    boolean nice = (new File(dir+"/Check"+number)).mkdir();
                    if(!nice){
                        System.out.println("CANNOT CREATE DIR: Check"+number+".");
                        System.out.println("PLEASE CHECK YOUR PERMISSIONS.");
                        System.exit(0);
                    }
                    dirNames.add(dir+"/Check"+number);
                }
                else{
                    dirNames.add(dir+"/Check"+number);

                 }
                BufferedWriter bwrite = new BufferedWriter(new FileWriter(dir+"/Check"+number+"/Dif"+number,true));
                //System.out.println(name);
                names.add("Dif"+number);
                line = bout.readLine();
                //System.out.println(line.indexOf("\\end{lstlisting}"));
                while(line!=null && line.indexOf("\\end{lstlisting}")==-1){
                    //System.out.println(line);
                    bwrite.write(line);
                    bwrite.newLine();
                    line = bout.readLine();
                }
                bwrite.flush();
                bwrite.close();
            }

            if(line.indexOf("\\begin{runners}")==0){
                if(!(new File(dir+"/Check"+number)).exists()){
                    boolean nice = (new File(dir+"/Check"+number)).mkdir();
                    if(!nice){
                        System.out.println("CANNOT CREATE DIR: Check"+number+".");
                        System.out.println("PLEASE CHECK YOUR PERMISSIONS.");
                        System.exit(0);
                    }
                    dirNames.add(dir+"/Check"+number);
                }
                else{
                    dirNames.add(dir+"/Check"+number);

                 }
                BufferedWriter bwrite = new BufferedWriter(new FileWriter(dir+"/Check"+number+"/Dif"+number,true));
                //System.out.println(name);
                names.add("Dif"+number);
                bwrite.newLine();
                line = bout.readLine();
                //System.out.println(line.indexOf("\\end{lstlisting}"));
                while(line!=null && line.indexOf("\\end{runners}")==-1){
                    //System.out.println(line);
                    bwrite.write(line);
                    bwrite.newLine();
                    line = bout.readLine();
                }
                bwrite.flush();
                bwrite.close();
            }

            if(line.indexOf("**check_mark**")!=-1){
                //String secname = line.substring(9,line.length()-1);
                number++;
                NewSection(number,bout,dir);
            }
        }
    }

    public void ParseSubFile(String fNameSub, String dir){
        //System.out.println(fileName);
        
        BufferedReader bout;
        try {
            bout = new BufferedReader(new FileReader(fNameSub));
            String line = null;
            ClearOldChecks(dir);
            while ((line = bout.readLine()) != null){
                    if(line.indexOf("**check_mark**")!=-1){
                        count++;
                        //String name = line.substring(9,line.length()-1);
                        NewSection(count,bout,dir);
                    }
            }
            bout.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TexParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TexParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //Extracts file name from \input{fileLocation}
    public String getFileName(String line){
        int sindex = line.indexOf("{");
        int eindex = line.indexOf("}");
        return line.substring(sindex+1, eindex);
    }

    //Extracts Artigo11 from Artigo11/Artigo
    public String getFileDir(String file){
        int index = file.indexOf("/");
        return file.substring(0, index);
    }

    public void ParseText(){
        BufferedReader bout;
        try {
            bout = new BufferedReader(new FileReader(fileName));
            String line = null;
            while ((line = bout.readLine()) != null){
                    if(line.indexOf("\\input")!=-1){
                        ParseSubFile(getFileName(line)+".tex", getFileDir(getFileName(line)));
                    }
            }
            bout.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TexParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TexParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static public boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            for(int i=0; i<files.length; i++) {
                 if(files[i].isDirectory()) {
                   deleteDirectory(files[i]);
                 }
                 else {
                   files[i].delete();
                 }
            }
        }
        return( path.delete() );
    }

    private void ClearOldChecks(String dir) {
        File fdir = new File(dir);
        File[] list = fdir.listFiles();
        for(File f : list){
            if(f.isDirectory() && f.getName().indexOf("Check")!=-1){
                deleteDirectory(f);
            }
        }
        //throw new UnsupportedOperationException("Not yet implemented");
    }
}
